<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-form-item label="选择日期：" prop="timeDate">
                        <el-date-picker v-model="queryParams.timeDate" type="daterange" range-separator="至"
                            start-placeholder="开始时间" end-placeholder="结束时间" @change="handleTimeChange"
                            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="摘要：" prop="orderPrintStatus">
                        <el-select style="width: 120px;" v-model="queryParams.orderPrintStatus" clearable>
                            <el-option label="未打印" value="0"></el-option>
                            <el-option label="已打印" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="付款账号：" prop="orderPrintStatus">
                        <el-select style="width: 120px;" v-model="queryParams.orderPrintStatus" clearable>
                            <el-option label="未打印" value="0"></el-option>
                            <el-option label="已打印" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="付款状态：" prop="orderPrintStatus">
                        <el-select style="width: 120px;" v-model="queryParams.orderPrintStatus" clearable>
                            <el-option label="未打印" value="0"></el-option>
                            <el-option label="已打印" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收款方名称：" prop="workName">
                        <el-input style="width: 120px;" v-model="queryParams.workName" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="20" justify="space-between">
                    <el-col :span="1.5">
                        <el-row :gutter="20">
                            <el-col :span="1.5">
                                <el-button plain type="warning" @click="batchPayment">
                                    <i class="iconfont icon-daifukuan mr2"></i>
                                    批量付款</el-button>
                            </el-col>
                            <!-- <el-col :span="1.5">
                                <el-button plain @click="handlOpenOneClickBalance">
                                    <i class="iconfont icon-bi mr2"></i>
                                    一键平账</el-button>
                            </el-col> -->
                            <el-col :span="1.5">
                                <el-button plain type="success" icon="DocumentDelete">下载EXCEL</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button @click="hanleOpenBalancingAccounts(1)" plain type="primary">
                                    <i class="iconfont icon-banshou mr2"></i>
                                    平账历史记录</el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button @click="hanleOpenBalancingAccounts(2)" plain type="danger"
                                    icon="DocumentDelete">货损抵扣历史记录</el-button>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="1.5">
                        <div>
                            <strong class="mr20">总应付金额：{{ totalPayableAmount }}</strong>
                            <strong class="mr20">平账总金额：{{ balanceAccountsAmount }}</strong>
                            <strong>其货损抵扣总金额：{{ damageAmount }}</strong>
                        </div>
                    </el-col>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="dataList">
                <el-table-column label="所属公司" prop="companyName" align="center"></el-table-column>
                <el-table-column label="对账日期" prop="reconciliationDate" align="center"></el-table-column>
                <el-table-column label="收款方名称" prop="collectName" align="center"></el-table-column>
                <el-table-column label="摘要" align="center">
                    <template #default="scope">
                        {{ summary_type.filter((item: any) => item.value == scope.row.summary)[0].label }}
                    </template>
                </el-table-column>
                <el-table-column label="对账备注" prop="reconciliationRemark" align="center"></el-table-column>
                <el-table-column label="总金额" prop="totalAmount" align="center"></el-table-column>
                <el-table-column label="对账金额" prop="reconciliationAmount" align="center"></el-table-column>
                <el-table-column label="已付款金额" prop="paidAlready" align="center"></el-table-column>
                <el-table-column label="待付款金额" align="center">
                    <template #default="scope">
                        {{ scope.row.paidAlready && scope.row.reconciliationAmount ?
                            Number(scope.row.reconciliationAmount) -
                            Number(scope.row.paidAlready) : '' }}
                    </template>
                </el-table-column>
                <el-table-column label="付款状态" align="center">
                    <template #default="scope">
                        <span style="color: #F75F51" v-if="scope.row.payStatus == 0">未付款</span>
                        <span style="color: #E8A94D" v-else-if="scope.row.payStatus == 1">部分付款</span>
                        <span style="color: #68C23D" v-else-if="scope.row.payStatus == 2">已付款</span>
                    </template>
                </el-table-column>
                <el-table-column label="付款人/单位" prop="payer" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="200px">
                    <template #default="scope">
                        <el-tooltip content="付款">
                            <el-button link @click="handlOpenPayment(scope.row)" type="warning">
                                <i style="font-size: 18px;" class="iconfont icon-daifukuan"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content=" 对账详情">
                            <el-button @click="handlOpenReconciliationDetails(scope.row)" :style="{ fontSize: '18px' }"
                                link type="primary" icon="Document"></el-button>
                        </el-tooltip>
                        <el-tooltip content="付款详情">
                            <el-button link @click="handlOpenPaymentDetails(scope.row)" type="warning">
                                <i style="font-size: 18px;" class="iconfont icon-zijinzhuanzhang"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="一键平账">
                            <el-button link @click="handlOpenOneClickBalance(scope.row)">
                                <i style="font-size: 18px;" class="iconfont icon-bi"></i>
                            </el-button>
                        </el-tooltip>

                        <el-tooltip content="删除">
                            <el-button @click="handleDelete(scope.row)" :style="{ fontSize: '18px' }" link type="danger"
                                icon="Delete"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>

            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 付款 -->
        <Payment :visible="paymentVisible" :initList="paymentRow" :allPaymentCardList="allPaymentCardList"
            @close="handlOpenPaymentClose" @submit="getList" />
        <!-- 对账详情 -->
        <ReconciliationDetails :visible="reconciliationDetailsVisible" @close="handleReconciliationDetailsClose" />
        <!-- 付款详情 -->
        <PaymentDetails :visible="paymentDetailsVisible" :initList="paymentDetails" :summaryType="summary_type"
            :paymentDetailsRow="paymentDetailsRow" @close="paymentDetailsVisible = false" />
        <!-- 一键平账 -->
        <OneClickBalance :visible="oneClickBalanceVisible" :initList="oneClickBalanceObj" :summaryType="summary_type"
            @submit="getList" @close="oneClickBalanceVisible = false" />
        <!-- 历史记录 -->
        <HistoryRecords :visible="historyRecordsVisible" :initList="historyRecordsList" :summaryType="summary_type"
            :type="historyRecordsType" @close="historyRecordsVisible = false" />
    </div>
</template>
<script setup lang="ts">
import { type FormInstance } from 'element-plus';

import { getAccountsPayableListApi, deleteAccountsPayableApi } from '@/api/sj/financialManagement/accountsPayable'
import { getAllPaymentCardApi } from '@/api/sj/financialManagement/paymentCard/index'

/** 付款 */
import Payment from './components/payment.vue'
import usePayment from '@/hooks/financialManagement/accountsPayable/usePayment'

/** 对账详情 */
import ReconciliationDetails from './components/reconciliationDetails.vue';
import useReconciliationDetails from '@/hooks/financialManagement/accountsPayable/useReconciliationDetails'

/** 付款详情 */
import PaymentDetails from './components/paymentDetails.vue';

/** 一键平账 */
import OneClickBalance from './components/oneClickBalance.vue';
import useOneClickBalance from '@/hooks/financialManagement/accountsPayable/useOneClickBalance'

/** 历史记录 */
import HistoryRecords from './components/historyRecords.vue';
import useHistoryRecords from '@/hooks/financialManagement/accountsPayable/useHistoryRecords'

const { paymentVisible, paymentRow, batchPayment, handlOpenPayment, handlOpenPaymentClose } = usePayment();
const { oneClickBalanceVisible, oneClickBalanceObj, handlOpenOneClickBalance } = useOneClickBalance();
const { reconciliationDetailsVisible, paymentDetailsVisible, paymentDetailsRow,
    paymentDetails, handlOpenPaymentDetails, handlOpenReconciliationDetails, handleReconciliationDetailsClose } = useReconciliationDetails();

const { historyRecordsVisible, historyRecordsType, historyRecordsList, hanleOpenBalancingAccounts, } = useHistoryRecords();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const queryFormRef = ref<FormInstance>();

const { summary_type } = toRefs<any>(proxy?.useDict('summary_type'));


const data = reactive<pageDataOnlyQuery<any>>({
    queryParams: {
        timeDate: '',
        startDate: '',
        endDate: '',
        pageSize: 10,
        pageNum: 1
    }
});

const { queryParams } = toRefs(data);

const loading = ref(false);
const dataList = ref<any>([]);
const totalData = ref(0);
const voucherVisible = ref(false);
const allPaymentCardList = ref<any>([]);

const balanceAccountsAmount = ref('0');
const damageAmount = ref('0');
const totalPayableAmount = ref('0');

const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.startDate = '';
    queryParams.value.endDate = '';
    queryParams.value.timeDate = '';
    handleQuery();
};

/** 日期选择 */
const handleTimeChange = (val: any) => {
    queryParams.value.startDate = val[0];
    queryParams.value.endDate = val[1];
};

/** 列表删除 */
const handleDelete = (row: any) => {
    ElMessageBox.confirm('除后，此订单将转化为未对账状态，请问您确定么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            deleteAccountsPayableApi(row.id).then(() => {
                ElMessage({
                    type: 'success',
                    message: '删除成功!'
                });
                getList();
            });
        })
        .catch(() => { });
};

// 撤回
const handleWithdraw = (row: any) => {
    ElMessageBox.confirm('您确认要将此条收款信息撒回么？撤回后此条收入信总将返回到应收款中，已收到的货款也从对应收款卡中撒回，您确认么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            });
        })
        .catch(() => { });
};

const getList = async () => {
    loading.value = true;
    try {
        const { data, code } = await getAccountsPayableListApi(queryParams.value);

        if (code === 200) {
            loading.value = false;
            balanceAccountsAmount.value = data.balanceAccountsAmount
            damageAmount.value = data.damageAmount
            totalPayableAmount.value = data.totalPayableAmount
            dataList.value = data.dataList.records
            totalData.value = data.dataList.total
        }

    } catch (error) {
        loading.value = false;

    }
};

/** 获取所有收款卡 */
const getAllPaymentCard = async () => {
    const { data } = await getAllPaymentCardApi();
    allPaymentCardList.value = data;
};

onMounted(() => {
    getList();
    getAllPaymentCard();
});

</script>
<style lang="scss" scoped></style>